package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Notice;
import cn.wolfcode.mapper.NoticeMapper;
import cn.wolfcode.query.QueryObject;
import cn.wolfcode.service.INoticeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class NoticeServiceImpl implements INoticeService {

    @Autowired
    private NoticeMapper noticeMapper;


    @Override
    public void save(Notice notice) {
        //当前登录用户即为发布人员
        Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
        //设置当前发布人员
        notice.setIssuer(employee);
        //设置当前发布时间为当前时间
        notice.setPubDate(new Date());
        noticeMapper.insert(notice);
    }

    @Override
    public void delete(Long id) {
        //删除公告时需要将所有已读这个公告的员工的id全部删除
        //将中间关系也要删除
        noticeMapper.deleteRelation(id);
        noticeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Notice notice) {
        //当前登录用户即为发布人员
        Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
        //设置当前发布人员
        notice.setIssuer(employee);
        //设置当前发布时间为当前时间
        notice.setPubDate(new Date());
        noticeMapper.updateByPrimaryKey(notice);
    }

    @Override
    public Notice get(Long id) {
        return noticeMapper.selectByPrimaryKey(id);


    }

    @Override
    public List<Notice> listAll() {
        return noticeMapper.selectAll();
    }

    @Override
    public PageInfo<Notice> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize()); //对下一句sql进行自动分页
        List<Notice> notices = noticeMapper.selectForList(qo); //里面不需要自己写limit
        //获取当前登录用户的id
        Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
        Long eId = employee.getId();
        for (Notice notice : notices) {
            //获取当前公告的id
            Long nId = notice.getId();
            Notice noticeEmp = noticeMapper.selectByEmpId(nId, eId);
            if (noticeEmp!=null){
                notice.setRead(true);
            }

        }
        return new PageInfo<>(notices);
    }

    @Override
    public Notice selectByEmpId(Long nId,Long eId) {
        return noticeMapper.selectByEmpId(nId,eId);
    }

    @Override
    public void insertRelation(Long nId, Long eId) {
        noticeMapper.insertRelation(nId,eId);
    }
}
